package com.seo.proxy.replacer;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.seo.proxy.http.HttpRequest;

public class UrlReplacer {
	
	private static final Pattern URL_PATTERN = Pattern.compile("https?://[^\\s\\['\"]+");

	private int count;
	
	public int replaceURLs(HttpRequest request) throws IOException {
		count = 0;
		/*URL url = request.getUrl();
		if (url.getQuery() != null) {
			String newQUery = processPairs(request.getUrl().getQuery());
			URL newUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getPath() + "?" + newQUery);
			request.setUrl(newUrl);
		}*/
		if ("POST".equals(request.getMethod()) && request.getBody() != null && "application/x-www-form-urlencoded".equals(request.getContentType())) {
			request.setBody(processPairs(request.getBody()));
		}
		return count;
	}
	
	private String processPairs(String pairs) {
		StringTokenizer st = new StringTokenizer(pairs, "&");
		StringBuilder newPairs = new StringBuilder();
		while (st.hasMoreTokens()) {
			String pair = st.nextToken();
			int p = pair.indexOf("=");
			if (p >= 0) {
				String name = pair.substring(0, p);
				String value = pair.substring(p + 1);
				newPairs.append(name).append("=").append(encodeURL(replaceURLs(decodeURL(value))));
			} else {
				newPairs.append(replaceURLs(pair));
			}
		}
		return newPairs.toString();
	}
	
	private String encodeURL(String str) {
		try {
			return URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	private String decodeURL(String str) {
		try {
			return URLDecoder.decode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	private String replaceURLs(String value) {
		StringBuilder sb = new StringBuilder();
		Matcher matcher = URL_PATTERN.matcher(value);
		int end = 0;
		while (matcher.find()) {
			sb.append(value.substring(end, matcher.start()));
			sb.append(getNextURL(matcher.group()));
			end = matcher.end();
			count++;
		}
		sb.append(value.substring(end));
		return sb.toString();
	}

	private String getNextURL(String originalURL) {
		return originalURL;
	}

	public static void main(String[] args) throws IOException {
		String str = "asd asd http://aaaa.com/test asd asd";
		System.out.println(new UrlReplacer().replaceURLs(str));
	}
}
